package cn.kooki.app.duobao.presenter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.ImageSpan;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.kooki.app.duobao.R;
import cn.kooki.app.duobao.data.Bean.Index.GoodsItem;
import cn.kooki.app.duobao.data.Bean.User.record.RecordItem;
import cn.kooki.app.duobao.ui.Activity.Goods.MyCodeAcitvity;
import cn.kooki.app.duobao.ui.Activity.Goods.OtherGoodWinRecordActivity;
import cn.kooki.app.duobao.ui.Activity.User.LoginActivity;
import cn.kooki.app.duobao.ui.Activity.Share.ShareActivity;
import cn.kooki.app.duobao.ui.Activity.User.UserCenterActivity;
import cn.kooki.app.duobao.ui.Activity.Comm.WebViewActivity;
import cn.kooki.app.duobao.ui.widget.banner.DotView;
import cn.kooki.app.duobao.ui.widget.banner.SliderBanner;
import cn.kooki.app.duobao.ui.widget.banner.SliderBannerController;
import cn.kooki.app.duobao.util.ListUtils;
import cn.kooki.app.duobao.util.SharePreferencesUtils;
import cn.kooki.app.duobao.util.StringUtils;
import cn.kooki.app.duobao.util.TimeUtils;
import cn.kooki.app.duobao.util.manager.CountDownObserver;
import cn.kooki.app.duobao.util.manager.CountDownTimerManager;
import cn.kooki.app.duobao.util.manager.ResultCounTDownTimer;


/**
 * Created by xiong on 2015/12/15.
 */
public class HeaderController implements CountDownObserver, View.OnClickListener {

    private final View header;
    private final Context context;
    private GoodsItem item;
    @Bind(R.id.goods_free_label)
    ImageView goodsFreeLabel;
    @Bind(R.id.good_ten_label)
    ImageView goodTenLabel;
    @Bind(R.id.limit_duobao_id)
    ImageView limitDuobaoId;
    @Bind(R.id.custom_top_left_icon)
    ImageView customTopLeftIcon;
    @Bind(R.id.ad_viewpager)
    ViewPager adViewpager;
    @Bind(R.id.ad_indicator)
    DotView adIndicator;
    @Bind(R.id.slider)
    SliderBanner slider;
    @Bind(R.id.add_wish_icon)
    ImageView addWishIcon;
    @Bind(R.id.has_added_to)
    ImageView hasAddedTo;
    @Bind(R.id.wish_added_button)
    RelativeLayout wishAddedButton;
    @Bind(R.id.detail_title_state)
    TextView detailTitleState;
    @Bind(R.id.detail_title)
    TextView detailTitle;
    @Bind(R.id.detail_qihao)
    TextView detailQihao;
    @Bind(R.id.activity_container)
    LinearLayout activityContainer;
    @Bind(R.id.detail_countdown_qihao)
    TextView detailCountdownQihao;
    @Bind(R.id.detail_cdTitle)
    TextView detailCdTitle;
    @Bind(R.id.tv_willReveal_time)
    TextView tvWillRevealTime;
    @Bind(R.id.bt_willReveal_calaDet)
    Button btWillRevealCalaDet;
    @Bind(R.id.layout_countdown)
    RelativeLayout layoutCountdown;
    @Bind(R.id.layout_publisherr)
    TextView layoutPublisherr;

    @Bind(R.id.iv_progressbar_progress)
    ProgressBar ivProgressbarProgress;
    @Bind(R.id.tv_progressbar_total)
    TextView tvProgressbarTotal;
    @Bind(R.id.tv_progressbar_left)
    TextView tvProgressbarLeft;
    @Bind(R.id.layout_progressBar)
    FrameLayout layoutProgressBar;
    @Bind(R.id.limit_title_id)
    ImageView limitTitleId;
    @Bind(R.id.first_hour)
    TextView firstHour;
    @Bind(R.id.second_hour)
    TextView secondHour;
    @Bind(R.id.first_min)
    TextView firstMin;
    @Bind(R.id.second_min)
    TextView secondMin;
    @Bind(R.id.first_second)
    TextView firstSecond;
    @Bind(R.id.second_second)
    TextView secondSecond;
    @Bind(R.id.limit_countdown)
    LinearLayout limitCountdown;
    @Bind(R.id.iv_revealed_avatar)
    ImageView ivRevealedAvatar;
    @Bind(R.id.tv_revealed_onName)
    TextView tvRevealedOnName;
    @Bind(R.id.tv_revealed_onLocal)
    TextView tvRevealedOnLocal;
    @Bind(R.id.tv_revealed_onId)
    TextView tvRevealedOnId;
    @Bind(R.id.detail_open_qihao)
    TextView detailOpenQihao;
    @Bind(R.id.tv_revealed_onCost)
    TextView tvRevealedOnCost;
    @Bind(R.id.tv_revealed_onTime)
    TextView tvRevealedOnTime;
    @Bind(R.id.detail_lkTitle)
    TextView detailLkTitle;
    @Bind(R.id.tv_revealed_onLuck)
    TextView tvRevealedOnLuck;
    @Bind(R.id.bt_revealed_calaDet)
    Button btRevealedCalaDet;
    @Bind(R.id.layout_revealed)
    RelativeLayout layoutRevealed;
    @Bind(R.id.good_detail_real_winner)
    ImageView goodDetailRealWinner;
    @Bind(R.id.reasionTextId)
    TextView reasionTextId;
    @Bind(R.id.firstReasionTextId)
    TextView firstReasionTextId;
    @Bind(R.id.secondReasionTextId)
    TextView secondReasionTextId;
    @Bind(R.id.threeReasionTextId)
    TextView threeReasionTextId;
    @Bind(R.id.realWinner)
    RelativeLayout realWinner;
    @Bind(R.id.tv_mycodeTotal)
    TextView tvMycodeTotal;
    @Bind(R.id.layout_mycodeListWp)
    TableLayout layoutMycodeListWp;
    @Bind(R.id.layout_myCodes)
    LinearLayout layoutMyCodes;
    @Bind(R.id.bt_layout_viewDetail)
    RelativeLayout btLayoutViewDetail;
    @Bind(R.id.bt_layout_winRecord)
    RelativeLayout btLayoutWinRecord;
    @Bind(R.id.bt_layout_shareDetail)
    RelativeLayout btLayoutShareDetail;
    @Bind(R.id.good_detail_allin)
    TextView goodDetailAllin;
    @Bind(R.id.tv_jointime_begin)
    TextView tvJointimeBegin;
    @Bind(R.id.tv_empty)
    TextView tvEmpty;

    private ArrayList<String> urls = new ArrayList<>();
    private SliderBannerController controller;
    private StringBuilder builder;
    private static final int countDownInterval = 10;

    public HeaderController(View header, Context context) {
        this.header = header;
        this.context = context;
        ButterKnife.bind(this, header);
        btLayoutShareDetail.setOnClickListener(this);
        btLayoutViewDetail.setOnClickListener(this);
        btLayoutWinRecord.setOnClickListener(this);
        layoutRevealed.setOnClickListener(this);
        btWillRevealCalaDet.setOnClickListener(this);
        btRevealedCalaDet.setOnClickListener(this);
        controller = new SliderBannerController(slider, context.getApplicationContext());
    }

    private CountCompeleteListener listener;

    @Override
    public void onClick(View v) {
        if (v == btLayoutShareDetail) {
            Intent intent = new Intent(context, ShareActivity.class);
            context.startActivity(intent);
        }
        if (v == layoutRevealed && item != null) {

            Intent intent = new Intent(context, UserCenterActivity.class);
            intent.putExtra("uid", item.getQ_uid());
            context.startActivity(intent);

        }
        if (v == btLayoutViewDetail && item != null) {
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.putExtra("title", "图文详情");
            intent.putExtra("id", item.getId());
            intent.putExtra("qishu", item.getQishu());
            context.startActivity(intent);
        }
        if (v == btLayoutWinRecord && item != null) {
            Intent intent = new Intent(context, OtherGoodWinRecordActivity.class);
            intent.putExtra("id", item.getGid());
            context.startActivity(intent);
        }

        if (v == btWillRevealCalaDet && item != null || v == btRevealedCalaDet && item != null) {
            Intent intent = new Intent(context, WebViewActivity.class);
            intent.putExtra("title", "计算结果");
            intent.putExtra("id", item.getGid());
            intent.putExtra("qishu", item.getQishu());
            intent.putExtra("type", WebViewActivity.REUSLT_TYPE);
            context.startActivity(intent);
        }
    }


    public interface CountCompeleteListener {
        void onCompelte();
    }


    public void setCompleteListener(CountCompeleteListener listener) {
        this.listener = listener;
    }

    public void setItem(GoodsItem item) {
        this.item = item;
    }

    public void refeshView() {
        if (item != null) {
            if (!ListUtils.isEmpty(item.getPicarr())) {
                urls.clear();
                urls.addAll(item.getPicarr());
            }

            if (TextUtils.isEmpty(item.getQ_uid()) && StringUtils.nullSafeParseInt(item.getStatus()) == 1) {
                ResultCounTDownTimer timer = new ResultCounTDownTimer(item.getNew_time(), countDownInterval);

                timer.setCallback(new ResultCounTDownTimer.TimerCallback() {
                    @Override
                    public void notice(long millisUntilFinished) {
                        item.setNew_time((int) millisUntilFinished);
                        if (tvWillRevealTime != null) {
                            tvWillRevealTime.setText(CountDownTimerManager.getInstance().transtime(item.getNew_time()));
                        }
                    }

                    @Override
                    public void finish() {
                        item.setNew_time(0);
                        if (item.getNew_time() == 0) {
                            if (listener != null) {
                                listener.onCompelte();
                            }
                        }
                    }
                });
                timer.start();
            }
            if (goodTenLabel != null) {
                goodTenLabel.setVisibility(item.getYunjiage().equals("10") ? View.VISIBLE : View.GONE);
                controller.play(urls);
                if (!TextUtils.isEmpty(item.getQishu())) {
                    detailQihao.setText("期号 : " + item.getQishu());
                }
                builder = new StringBuilder();
                int currt = StringUtils.nullSafeParseInt(item.getCanyurenshu());
                int total = StringUtils.nullSafeParseInt(item.getZongrenshu());

                String leftstring = "剩余:<font color='blue'>" + (total - currt) + "</font>";
                tvProgressbarLeft.setText(Html.fromHtml(leftstring));
                tvProgressbarTotal.setText("总需:" + item.getZongrenshu());
                ivProgressbarProgress.setMax(total);
                ivProgressbarProgress.setProgress(currt);
                SpannableStringBuilder style = new SpannableStringBuilder(" " + item.getTitle() + " " + item.getTitle2());
                Bitmap b = BitmapFactory.decodeResource(context.getResources(), compantState());
                style.setSpan(new ImageSpan(context, b, ImageSpan.ALIGN_BASELINE), 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(new ForegroundColorSpan(Color.parseColor("#ff676767")), 1, item.getTitle().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                style.setSpan(new ForegroundColorSpan(Color.parseColor("#ffdb3652")), item.getTitle().length() + 1,
                        item.getTitle().length() + item.getTitle2().length() + 2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                detailTitle.setText(style);
                detailTitle.setVisibility(View.VISIBLE);
                int status = StringUtils.nullSafeParseInt(item.getStatus());
                if (status == 0) {
                    layoutProgressBar.setVisibility(View.VISIBLE);
                    layoutCountdown.setVisibility(View.GONE);
                    layoutRevealed.setVisibility(View.GONE);
                } else if (status == 1) {
                    layoutProgressBar.setVisibility(View.GONE);
                    layoutCountdown.setVisibility(View.VISIBLE);
                    detailCountdownQihao.setText(item.getQishu());
                    tvWillRevealTime.setText(CountDownTimerManager.getInstance().transtime(item.getNew_time()));
                    layoutRevealed.setVisibility(View.GONE);
                } else {
                    layoutProgressBar.setVisibility(View.GONE);
                    layoutCountdown.setVisibility(View.GONE);

                    layoutRevealed.setVisibility(View.VISIBLE);
                    String revealname = "获奖者: <font color='blue'>" + item.getQ_user() + "</font>";
                    tvRevealedOnName.setText(Html.fromHtml(revealname));

                    String uid = context.getString(R.string.uid_string);
                    uid = String.format(uid, item.getQ_uid());
                    detailOpenQihao.setText(item.getQishu());
                    tvRevealedOnLocal.setText("(" + item.getQ_user_addr() + ")");
                    String coust = "本期参与:<font color='red'>" + item.getQ_num() + "</font>人次";
                    tvRevealedOnCost.setText(Html.fromHtml(coust));
                    tvRevealedOnId.setText(uid);
                    tvRevealedOnLuck.setText(item.getQ_user_code());
                    if (item.getQ_end_time() != null) {
                        tvRevealedOnTime.setText("揭晓时间:" + TimeUtils.getTime(item.getQ_end_time()));
                    }
                }
                boolean ISLOGIN = SharePreferencesUtils.getBoolean(context, SharePreferencesUtils.ISLOGIN);
                if (ISLOGIN) {
                    if (TextUtils.isEmpty(item.getUname_go_record())){
                        tvMycodeTotal.setText("您没有参与本期夺宝");
                        tvMycodeTotal.setOnClickListener(null);
                    }else {
                        Gson gson = new Gson();
                        final ArrayList<String> counts = gson.fromJson(item.getUname_go_record(),
                                new TypeToken<ArrayList<String>>() {
                        }.getType());
                        tvMycodeTotal.setText("您参与了"+counts.size()+"人次的夺宝,点击详情");
                        tvMycodeTotal.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                RecordItem recordItem = new RecordItem();
                                recordItem.title = item.getTitle();
                                recordItem.q_num = counts.size();
                                recordItem.qishu = item.getQishu();
                                Intent intent = new Intent(context, MyCodeAcitvity.class);
                                intent.putExtra("codes", counts);
                                intent.putExtra("item", recordItem);
                                context.startActivity(intent);
                            }
                        });
                    }

                } else {
                    String loginlook = context.getString(R.string.loginforlook);
                    tvMycodeTotal.setText(Html.fromHtml(loginlook));
                    tvMycodeTotal.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(context, LoginActivity.class);
                            context.startActivity(intent);
                        }
                    });
                }

            }
        }
    }

    private int compantState() {
        switch (StringUtils.nullSafeParseInt(item.getStatus())) {
            case 0:
                return R.drawable.ic_perioding;
            case 1:
                return R.drawable.ic_periodwillreveal;
            case 2:
                return R.drawable.ic_periodrevealed;
            default:
                return R.drawable.ic_perioding;
        }

    }

    public void unbindView() {
        ButterKnife.unbind(this);

    }

    @Override
    public void onChanged(GoodsItem noticeitem) {
        if (item != null) {

        }
    }
}
